<?php
require '../db.php';
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$settings_file = __DIR__ . '/../settings.json';
$settings = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : [
    'max_upload_size' => 10 * 1024 * 1024,
    'allowed_file_types' => ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'doc', 'docx'],
    'upload_dir' => 'uploads/'
];
$upload_dir = __DIR__ . '/../' . $settings['upload_dir'];

if (isset($_GET['delete'])) {
    $stmt = $conn->prepare("SELECT path FROM files WHERE id = ?");
    $stmt->bind_param("i", $_GET['delete']);
    $stmt->execute();
    $file = $stmt->get_result()->fetch_assoc();
    if ($file) {
        unlink($file['path']);
        $stmt = $conn->prepare("DELETE FROM files WHERE id = ?");
        $stmt->bind_param("i", $_GET['delete']);
        $stmt->execute();
    }
    header("Location: files.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        exit;
    }
    $name = $_FILES['file']['name'];
    $tmp = $_FILES['file']['tmp_name'];
    $path = $upload_dir . time() . '_' . basename($name);
    $user_id = $_SESSION['user_id'];

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, $settings['allowed_file_types'])) {
        echo "<script>alert('不允许的文件类型！仅支持: " . htmlspecialchars(implode(', ', $settings['allowed_file_types'])) . "'); history.back();</script>";
        exit;
    }
    if ($_FILES['file']['size'] > $settings['max_upload_size']) {
        echo "<script>alert('文件超过最大限制 " . round($settings['max_upload_size'] / (1024 * 1024), 2) . "MB！'); history.back();</script>";
        exit;
    }

    if (!is_dir($upload_dir) && !mkdir($upload_dir, 0755, true)) {
        echo "<script>alert('无法创建上传目录！'); history.back();</script>";
        exit;
    }
    if (!is_writable($upload_dir)) {
        echo "<script>alert('上传目录不可写！'); history.back();</script>";
        exit;
    }

    if (move_uploaded_file($tmp, $path)) {
        $stmt = $conn->prepare("INSERT INTO files (name, path, user_id) VALUES (?, ?, ?)");
        $stmt->bind_param("ssi", $name, $path, $user_id);
        if ($stmt->execute()) {
            header("Location: files.php");
            exit;
        } else {
            unlink($path);
            echo "<script>alert('数据库错误：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
        }
    } else {
        $error = $_FILES['file']['error'];
        echo "<script>alert('文件移动失败，错误码：" . $error . "'); history.back();</script>";
    }
}

$result = $conn->query("SELECT f.id, f.name, f.upload_time, u.username FROM files f JOIN users u ON f.user_id = u.id");
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件管理</title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <nav class="navbar navbar-expand-lg <?= $settings['theme'] === 'dark' ? 'navbar-dark bg-dark' : 'navbar-light bg-light' ?>">
        <div class="container">
            <a class="navbar-brand" href="index.php">后台管理</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="../index.php">网站前台</a></li>
                    <li class="nav-item"><a class="nav-link" href="users.php">用户管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="files.php">文件管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="categories.php">分类管理</a></li>
                    <li class="nav-item"><a class="nav-link" href="settings.php">网站设置</a></li>
                    <li class="nav-item"><a class="nav-link" href="../logout.php">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container py-5">
        <h2>文件管理</h2>
        <form method="POST" enctype="multipart/form-data" class="mb-3">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="input-group">
                <input type="file" class="form-control" name="file" required>
                <button type="submit" class="btn btn-primary">上传</button>
            </div>
            <small class="form-text text-muted">最大 <?= round($settings['max_upload_size'] / (1024 * 1024), 2) ?>MB，仅支持 <?= htmlspecialchars(implode(', ', $settings['allowed_file_types'])) ?></small>
        </form>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>上传时间</th>
                    <th>作者</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php $index = 1; while ($file = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= $index++ ?></td>
                        <td><?= htmlspecialchars($file['name']) ?></td>
                        <td><?= $file['upload_time'] ?></td>
                        <td><?= htmlspecialchars($file['username']) ?></td>
                        <td>
                            <a href="../download.php?id=<?= $file['id'] ?>" class="btn btn-primary btn-sm">下载</a>
                            <a href="files.php?delete=<?= $file['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('确认删除？')">删除</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>